package controllers

import (
	//"encoding/json"
	"fmt"
	"net/url"
	"strconv"
	"time"

	"qkstatis/errorcode"
	"qkstatis/fxlsx"
	"qkstatis/statis"

	log "github.com/cihub/seelog"
	"github.com/tealeg/xlsx"
)

type QKStatisController struct {
	//	URLSignController
	SCLoginedController
}

//获取营收列表
//@router /all-profit/list [post]
func (p *QKStatisController) AllProfitList() {
	defer p.Output("AllProfitList")

	ltype, _ := p.GetInt("type", 0)
	timeRange := p.GetString("time_range", "")

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}

	req := &statis.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &statis.ShowItemResp{}

	err := statis.GetStatisService().GetAllProfit(req, resp, ltype, timeRange)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}

//获取加盟商/洗衣点营收列表
//@router /lr-profit/list [post]
func (p *QKStatisController) League2WashRoomProfitList() {
	defer p.Output("League2WashRoomProfitList")

	ltype, _ := p.GetInt("type", 0)
	timeRange := p.GetString("time_range", "")
	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	sessionId := p.GetString("sessionid", "")

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}

	req := &statis.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &statis.ShowItemResp{}

	err := statis.GetStatisService().GetLWProfit(req, resp, ltype, timeRange, leagueId, washRoomId, sessionId)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}

//获取洗衣机营收列表
//@router /washer-profit/list [post]
func (p *QKStatisController) WasherProfitList() {
	defer p.Output("WasherProfitList")

	ltype, _ := p.GetInt("type", 0)
	timeRange := p.GetString("time_range", "")
	washerId := p.GetString("washer_id", "")

	body := p.Ctx.Input.RequestBody
	qs, _ := url.ParseQuery(string(body))
	start, _ := strconv.Atoi(qs.Get("start"))
	length, _ := strconv.Atoi(qs.Get("length"))
	if length == 0 {
		length = 10
	}

	req := &statis.ShowItemReq{}
	req.PageIndex = start / length
	req.PageSize = length
	req.Role = false

	resp := &statis.ShowItemResp{}

	err := statis.GetStatisService().GetWasherProfit(req, resp, ltype, timeRange, washerId)
	p.Resp["code"] = resp.Code
	p.Resp["msg"] = resp.Msg
	if err == nil {
		p.Resp["data"] = resp.Data
		p.Resp["has_more"] = resp.HasMore
		p.Resp["recordsTotal"] = resp.Total
		p.Resp["recordsFiltered"] = resp.Total
		p.Resp["draw"], _ = strconv.Atoi(qs.Get("draw"))
		return
	} else {
		p.Resp["msg"] = err.Error()
	}
}

//获取时间
//@router /times/get [get]
func (p *QKStatisController) GetTimes() {
	defer p.Output("GetTimes")

	ltype, _ := p.GetInt("type", 0)
	start := p.GetString("start", "")

	if err, data := statis.GetStatisService().GetTimes(ltype, start); err == nil {
		p.Resp["code"] = errorcode.EC_GL_SUCCESS
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
		p.Resp["data"] = data
	} else {
		p.Resp["code"] = errorcode.EC_GL_INTERNAL_ERROR
		p.Resp["msg"] = err.Error()
	}
}

//导出订单列表
//@router  /list-xlsx [get]
func (p *QKStatisController) ExportList() {
	defer p.Output("ExportList")

	ltype, _ := p.GetInt("type", 0)
	timeRange := p.GetString("time_range", "")
	leagueId := p.GetString("league_id", "")
	washRoomId := p.GetString("washroom_id", "")
	stype, _ := p.GetInt("stype", 0)
	sessionId := p.GetString("sessionid", "")

	/*	body := p.Ctx.Input.RequestBody
		log.Debugf("recv body: %s", string(body))
		req := &exportOrderListReq{}
		if err := json.Unmarshal(body, req); err != nil {
			log.Errorf("json err; err:%s", err.Error())
			p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
			p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
			return
		}*/
	if stype == 0 || ltype == 0 {
		log.Errorf("invalid body param; stype and dtype is not allowed empty, stype:%d, dtype:%d", stype, ltype)
		p.Resp["code"] = errorcode.EC_GL_INVALID_JSON_BODY
		p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_INVALID_JSON_BODY)
		return
	}

	ok, start, end := statis.GetStatisService().IsValidTimeRange(ltype, timeRange)
	if !ok {
		log.Errorf("无效的时间范围, dtype:%d, timeRange:%s", ltype, timeRange)
		p.Resp["code"] = errorcode.EC_QKSTATIS_INVALID_TIME_RANGE
		p.Resp["msg"] = "无效的时间范围"
		return
	}
	conditions := map[string]interface{}{
		"date_flag >= ?": start,
		"date_flag <= ?": end,
	}

	var urlPath string
	switch stype {
	case 1:
		data, _ := statis.GetAllProfitStatisService().ListAllProfit(ltype, conditions, false)
		urlPath = p.exportAll(data)
	case 2:
		if leagueId != "0000" {
			conditions["league_id = ?"] = leagueId
		}
		data, _ := statis.GetLeagueProfitStatisService().ListLeagueProfit(sessionId, ltype, conditions, false)
		urlPath = p.exportLeague(data)
	case 3:
		conditions["wash_room_id = ?"] = washRoomId
		data, _ := statis.GetWashRoomProfitStatisService().ListWashRoomProfit(sessionId, ltype, conditions, false)
		urlPath = p.exportWashRoom(data)
	}
	p.Resp["code"] = errorcode.EC_GL_SUCCESS
	p.Resp["msg"] = errorcode.Msg(errorcode.EC_GL_SUCCESS)
	p.Resp["url"] = urlPath
}

//导出营收信息列表
func (p *QKStatisController) exportAll(data []*statis.AllProfit) string {
	file := xlsx.NewFile()
	sheet, _ := file.AddSheet("总营收列表")
	row := sheet.AddRow()
	row.AddCell().SetValue("日期")
	row.AddCell().SetValue("洗衣量")
	row.AddCell().SetValue("充值量")
	row.AddCell().SetValue("洗衣人数")
	row.AddCell().SetValue("充值人数")
	row.AddCell().SetValue("净总营收")
	row.AddCell().SetValue("净洗衣营收")
	row.AddCell().SetValue("净充值营收")
	row.AddCell().SetValue("充值优惠额")
	row.AddCell().SetValue("洗衣优惠额")
	row.AddCell().SetValue("轻币洗衣优惠额")
	row.AddCell().SetValue("现金洗衣优惠额	")
	row.AddCell().SetValue("洗衣轻币支付额")
	row.AddCell().SetValue("洗衣轻币支付")
	row.AddCell().SetValue("洗衣总营收")
	for _, ap := range data {
		row = sheet.AddRow()
		row.AddCell().SetValue(ap.DateFlag)
		row.AddCell().SetValue(ap.WashingOrders)
		row.AddCell().SetValue(ap.RechargeOrders)
		row.AddCell().SetValue(ap.WashingPeer)
		row.AddCell().SetValue(ap.RechargePeer)
		row.AddCell().SetValue(ap.Total)
		row.AddCell().SetValue(ap.WashingCashPart)
		row.AddCell().SetValue(ap.RechargeTotal)
		row.AddCell().SetValue(ap.RechargeDiscount)
		row.AddCell().SetValue(ap.WashingDiscount)
		row.AddCell().SetValue(ap.WashingCashDiscount)
		row.AddCell().SetValue(ap.WashingQBDiscount)
		row.AddCell().SetValue(ap.WashingQBPart)
		row.AddCell().SetValue(ap.WashingTotal)
	}
	xlsxFilePath, urlPath := fxlsx.GetXLSXFilePath(fmt.Sprintf("%d", time.Now().Unix()))
	file.Save(xlsxFilePath)
	return urlPath
}

//导出加盟商营收信息列表
func (p *QKStatisController) exportLeague(ap []*statis.LeagueProfit) string {
	file := xlsx.NewFile()
	sheet, _ := file.AddSheet("营收列表")
	row := sheet.AddRow()
	row.AddCell().SetValue("日期")
	row.AddCell().SetValue("加盟商")
	row.AddCell().SetValue("洗衣量")
	row.AddCell().SetValue("洗衣营收")
	row.AddCell().SetValue("洗衣净营收")
	row.AddCell().SetValue("洗衣优惠额")
	row.AddCell().SetValue("洗衣人数")
	row.AddCell().SetValue("激活洗衣机")
	row.AddCell().SetValue("有效洗衣机")
	row.AddCell().SetValue("严格机效（单/台）")
	row.AddCell().SetValue("严格机效（元/台）")
	row.AddCell().SetValue("宽松机效（单/台）")
	row.AddCell().SetValue("宽松机效（元/台）")
	for _, lp := range ap {
		row = sheet.AddRow()
		row.AddCell().SetValue(lp.DateFlag)
		row.AddCell().SetValue(lp.LeagueName)
		row.AddCell().SetValue(lp.WashingOrder)
		row.AddCell().SetValue(lp.WashingTotal)
		row.AddCell().SetValue(lp.WashingProfit)
		row.AddCell().SetValue(lp.WashingDiscount)
		row.AddCell().SetValue(lp.WashingPeer)
		row.AddCell().SetValue(lp.WasherNumActive)
		row.AddCell().SetValue(lp.WasherNumUse)
		row.AddCell().SetValue(lp.So1m)
		row.AddCell().SetValue(lp.Sp1m)
		row.AddCell().SetValue(lp.Lo1m)
		row.AddCell().SetValue(lp.Lp1m)
	}
	xlsxFilePath, urlPath := fxlsx.GetXLSXFilePath(fmt.Sprintf("%d", time.Now().Unix()))
	file.Save(xlsxFilePath)
	return urlPath
}

//导出洗衣点营收信息列表
func (p *QKStatisController) exportWashRoom(lp []*statis.WashRoomProfit) string {
	file := xlsx.NewFile()
	sheet, _ := file.AddSheet("营收列表")
	row := sheet.AddRow()
	row.AddCell().SetValue("日期")
	row.AddCell().SetValue("加盟商")
	row.AddCell().SetValue("洗衣量")
	row.AddCell().SetValue("洗衣营收")
	row.AddCell().SetValue("洗衣人数")
	row.AddCell().SetValue("激活洗衣机")
	row.AddCell().SetValue("有效洗衣机")
	row.AddCell().SetValue("严格机效（单/台）")
	row.AddCell().SetValue("严格机效（元/台）")
	row.AddCell().SetValue("宽松机效（单/台）")
	row.AddCell().SetValue("宽松机效（元/台）")
	for _, wrp := range lp {
		row = sheet.AddRow()
		row.AddCell().SetValue(wrp.DateFlag)
		row.AddCell().SetValue(wrp.LeagueName)
		row.AddCell().SetValue(wrp.WashingOrder)
		row.AddCell().SetValue(wrp.WashingProfit)
		row.AddCell().SetValue(wrp.WashingPeer)
		row.AddCell().SetValue(wrp.WasherNumActive)
		row.AddCell().SetValue(wrp.WasherNumUse)
		row.AddCell().SetValue(wrp.So1m)
		row.AddCell().SetValue(wrp.Sp1m)
		row.AddCell().SetValue(wrp.Lo1m)
		row.AddCell().SetValue(wrp.Lp1m)
	}
	xlsxFilePath, urlPath := fxlsx.GetXLSXFilePath(fmt.Sprintf("%d", time.Now().Unix()))
	file.Save(xlsxFilePath)
	return urlPath
}
